<?php
namespace common\models;

/**
 * Class FnModel
 * @package common\models
 * 共有操作函数库
 */
class FnModel
{

    /**
     * 生成16位的散列值
     * @param $str
     * @param string $algo 支持支md5和fnv164
     * @return string
     */
    public static function shortHash($str, $algo = 'fnv164')
    {
        if (!in_array($algo, ['fnv164', 'md5'])) {
            return '';
        }

        $hash = '';
        switch ($algo) {
            case 'md5' :
                $hash = (string)substr(md5($str), 8, 16);
                break;
            case 'fnv164' :
                $hash = hash($algo, $str);
                break;
            default :
                break;
        }

        return $hash;
    }

    /**
     * 生成签名
     * @param array $params
     * @param $secret
     * @param bool $skipEmpty 是否跳过空值
     * @param bool $toUpper 签名结果是否大写
     * @param string $joinSecretKey 拼接的密钥key名
     * @return string
     */
    public static function makeSign(array $params, $secret, $skipEmpty = false, $toUpper = false, $joinSecretKey = '')
    {
        if (empty($params)) {
            return '';
        }
        $str = "";
        ksort($params);
        foreach ($params as $k => $v) {
            if ($skipEmpty && $v == "") {
                continue;
            }
            $str .= '&' . $k . '=' . $v;
        }
        $str = ltrim($str, '&') . ($joinSecretKey ? "&$joinSecretKey=" : '') . $secret;
        $sign = md5($str);

        return $toUpper ? strtoupper($sign) : $sign;
    }

    /**
     * 生成指定长度随机数
     * @param int $length
     * @return string
     */
    public static function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }

    /**
     * Base64 for URL parameters/filenames
     * Defaults to dropping the padding on encode since it's not required for decoding, and keeps the URL free of % encodings.
     */
    public static function base64UrlEncode($data, $pad = null)
    {
        $data = str_replace(array('+', '/'), array('-', '_'), base64_encode($data));
        if (!$pad) {
            $data = rtrim($data, '=');
        }
        return $data;
    }

    /**
     * Base64 for URL parameters/filenames
     * Defaults to dropping the padding on encode since it's not required for decoding, and keeps the URL free of % encodings.
     */
    public static function base64UrlDecode($data)
    {
        return base64_decode(str_replace(array('-', '_'), array('+', '/'), $data));
    }

    /**
     * @param $accountNumber
     * @param string $type
     * @return string|string[]|null
     * 获取账号（手机号、邮箱）的隐藏字符串
     */
    public static function getHideAccount($accountNumber,$type = "phone"){
        switch($type){
            case "phone":
            {
                $pattern = '/(\d{3})(\d{4})(\d{4})/i';
                $replacement = '$1****$3';
                $result = preg_replace($pattern, $replacement,$accountNumber);
            }
                break;
            case  "email":
            {
                $arr = explode('@', $accountNumber);
                $rest = substr($arr[0], 0, -2);
                $arr[0] = str_replace($rest, str_repeat('*', strlen($rest)), $arr[0]);
                $result = $arr[0]."@".$arr[1];
            }
                break;
            default:
            {
                $pattern = '/(\d{3})(\d{4})(\d{4})/i';
                $replacement = '$1****$3';
                $result = preg_replace($pattern, $replacement,$accountNumber);
            }

        }
        return $result;
    }

    /**
     * @param string $phone
     * @return bool|false|int
     * 校验手机号码
     */
    public static function validatePhone($phone='')
    {
        if (!$phone) {
            return false;
        }
        return preg_match("/^1\d{10}$/", trim((string)$phone));
    }
}
